package com.erp.web.erp.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.erp.base.base.Page;
import com.erp.base.business.entity.AppUser;
import com.erp.base.business.entity.ExpertApprovalRecord;
import com.erp.base.business.entity.ExpertUser;
import com.erp.base.business.entity.MemberConsultAnswer;
import com.erp.base.business.entity.MemberConsultQuestion;
import com.erp.base.business.entity.ServerUserRel;
import com.erp.base.business.service.AppUserService;
import com.erp.base.business.service.ExpertApprovalRecordService;
import com.erp.base.business.service.ExpertUserService;
import com.erp.base.business.service.MemberConsultAnswerService;
import com.erp.base.business.service.MemberConsultQuestionService;
import com.erp.base.business.service.RegionService;
import com.erp.base.business.service.ServerService;
import com.erp.base.business.service.ServerUserRelService;
import com.erp.base.common.config.BootdoConfig;
import com.erp.base.common.config.Constant;
import com.erp.base.common.entity.Email;
import com.erp.base.common.entity.File;
import com.erp.base.common.service.FileService;
import com.erp.base.common.service.MailService;
import com.erp.base.common.utils.AppUserUtils;
import com.erp.base.common.utils.FileType;
import com.erp.base.common.utils.FileUtil;
import com.erp.base.common.utils.JedisUtils;
import com.erp.base.common.utils.JsonMapper;
import com.erp.base.common.utils.OperationResult;
import com.erp.base.common.utils.UUIDUtils;

@Service
public class ErpUserService {
	
	private static Logger logger=LoggerFactory.getLogger(ErpUserService.class);
	@Autowired
	private AppUserService appUserService;
	@Autowired
	private ExpertUserService expertUserService;
	@Autowired
	private MemberConsultQuestionService memberConsultQuestionService;
	@Autowired
	private MemberConsultAnswerService memberConsultAnswerService;
	@Autowired
	private ServerService serverService;
	@Autowired
	private ExpertApprovalRecordService expertApprovalRecordService;
	@Autowired
    private BootdoConfig bootdoConfig;
	@Autowired
	private FileService sysFileService;
	@Autowired
	private MailService mailService;
	@Autowired
	private RegionService regionService;
	@Autowired
	private ServerUserRelService serverUserRelService;

	
	public OperationResult login(String username, String password,HttpServletRequest request) {
		if(StringUtils.isBlank(username)){
			return OperationResult.buildFailureResult("用户名不能为空!");
		}
		if(StringUtils.isBlank(password)){
			return OperationResult.buildFailureResult("密码不能为空!");
		}
		String key=Constant.REDIS_PRIFIX_ERP+username;
		String value=JedisUtils.get(key);
		if(StringUtils.isNotBlank(value)&&Long.parseLong(value)>=Constant.LOGIN_RETRY_TIMES){
			JedisUtils.expire(key, Constant.REDIS_TIME_OUT);
			return OperationResult.buildFailureResult("密码错误次数过多，锁定30分钟！");
		}
		AppUser appUser = appUserService.loginSuccess(username, password);
		if(appUser==null){
			value=JedisUtils.get(key);
			if(StringUtils.isBlank(value)){
				value="1";
				JedisUtils.set(key, value);
				JedisUtils.expire(key, Constant.REDIS_TIME_OUT);
			}else{
				value=String.valueOf(Long.parseLong(value)+1);
				JedisUtils.set(key,value);
				JedisUtils.expire(key, Constant.REDIS_TIME_OUT);
			}
			logger.info("用户名不存在/密码错误,username="+username+";已经试用:"+value+"次！");
			return OperationResult.buildFailureResult("用户名不存在/密码错误!");
		}
		if(Constant.USER_NOT_ACTIVATED.equals(appUser.getIsActivate())){
			return OperationResult.buildFailureResult("该用户还未激活，请登录邮箱:"+appUser.getEmail()+"进行激活！");
		}
		appUser.setLastLoginTime(new Date());
		////更新登录时间
		appUserService.update(appUser);
		String token=UUIDUtils.getUUID();
		JedisUtils.set(Constant.REDIS_PRIFIX_ERP+token, JsonMapper.toJsonString(appUser), Constant.REDIS_TIME_OUT);
		Map<String, Object>data=new HashMap<String, Object>();
		data.put("appUser", appUser);
		data.put("token", token);
		//request.getSession().setAttribute("appUser", appUser);
		//删除存在redis的值
		JedisUtils.del(key);
		return OperationResult.buildSuccessResult("登录成功!", data);
	}

	public OperationResult register(AppUser appUser, HttpServletRequest request) {
		String username=appUser.getUsername();
		if(StringUtils.isBlank(username)){
			return OperationResult.buildFailureResult("用户名不能为空！");
		}
		if(!appUserService.isUniqueByUsername(username)){
			return OperationResult.buildFailureResult("用户名已经存在！");
		}
		String email=appUser.getEmail();
		if(StringUtils.isBlank(email)){
			return OperationResult.buildFailureResult("邮箱不能为空！");
		}
		if(!appUserService.isUniqueByEmail(email)){
			return OperationResult.buildFailureResult("邮箱已经存在！");
		}
		appUser.setIsActivate(Constant.USER_NOT_ACTIVATED);//注册默认激活状态为0：未激活
		String activateCode=UUIDUtils.getUUID();
		appUser.setActivateCode(activateCode);
		appUser.setMobile(username);
		appUser.setCreateBy(username);
		appUser.setCreateDate(new Date());
		appUser.setUpdateBy(username);
		appUser.setUpdateDate(new Date());
		
		appUser.setProvincialName(regionService.get(appUser.getProvincialId()).getName());
		appUser.setCityName(regionService.get(appUser.getCityId()).getName());
		appUser.setAreaName(regionService.get(appUser.getAreaId()).getName());
		
		//默认头像
		appUser.setImageUrl("/img/a8.jpg");
		appUserService.insert(appUser);
		appUser=appUserService.findAppUserByUserName(username);
		//发送验证邮箱
		Email mail=new Email();
		mail.setToUser(email);
		mail.setSubject("欢迎注册ERP服务系统");
		StringBuffer sb=new StringBuffer();
		String url=request.getHeader("host");
		String emailUrl="http://"+url+"/erp/index/activate?activateCode="+activateCode+"&id="+appUser.getId();
		sb.append("欢迎加入ERP服务系统!<br/>").append("亲爱的用户，你好!<br/>")
		  .append("你的邮箱是：").append(email).append("<br/>请点击以下链接验证你的邮箱地址!<br/>")
		  .append("<a href='").append(emailUrl).append("'>").append(emailUrl).append("</a>")
		  .append("<br/>如果以上链接无法访问，请将该网址复制并粘贴至新的浏览器窗口中。<br/>")
		  .append("祝您生活愉快，工作顺利！<br/>ERP服务系统团队敬上！");
		mail.setContent(sb.toString());
		mailService.sendHTMLMail(mail);
		return OperationResult.buildSuccessResult("注册成功！");
	}

	public OperationResult getMemberSelfQuestions(String isAnswer,HttpServletRequest request) {
		AppUser appUser=AppUserUtils.getCurrentUser(request);
		MemberConsultQuestion memberConsultQuestion=new MemberConsultQuestion();
		memberConsultQuestion.setUserId(appUser.getId());
		if(StringUtils.isNotBlank(isAnswer)){
			memberConsultQuestion.setIsAnswer(isAnswer);
		}
		return OperationResult.buildSuccessResult(memberConsultQuestionService.findList(memberConsultQuestion));
	}

	public OperationResult getMemberExpertQuestions(String isAnswer,Long userId, HttpServletRequest request) {
		Page<MemberConsultQuestion>page=Page.erpPage(request);
		MemberConsultQuestion memberConsultQuestion=new MemberConsultQuestion();
		ExpertUser expertUser=new ExpertUser();
		expertUser.setUserId(userId);
		List<ExpertUser> expertLists = expertUserService.findList(expertUser);
		if(expertLists==null||expertLists.isEmpty()||expertLists.size()>1){
			return OperationResult.buildFailureResult("专家id不存在");
		}
		memberConsultQuestion.setExpertId(expertLists.get(0).getId());
		if(StringUtils.isNotBlank(isAnswer)){
			memberConsultQuestion.setIsAnswer(isAnswer);
		}
		Map<String, Object>data=new HashMap<String, Object>();
		data.put("question", memberConsultQuestionService.findPage(page, memberConsultQuestion));
		data.put("expert", expertLists.get(0));
		return OperationResult.buildSuccessResult(data);
	}

	public OperationResult savememberAnswers(MemberConsultAnswer memberConsultAnswer, HttpServletRequest request) {
		MemberConsultQuestion memberConsultQuestion=memberConsultQuestionService.get(memberConsultAnswer.getMemberQuestionId());
		Long proposeId=memberConsultQuestion.getId();
		AppUser appUser= AppUserUtils.getCurrentUser(request);
		//如果当前登录人id和提出问题id一致，则回复类型type=0 并且将问题回答状态改为未回答(0)，否则type=1且问题状态改为回答(1)   ps(类型 ：0 发起者 1：回答者)
		if(proposeId.compareTo(appUser.getId())==0){
			memberConsultAnswer.setType("0");
			//更改问题回答状态
			memberConsultQuestion.setUpdateBy(appUser.getUsername());
			memberConsultQuestion.setUpdateDate(new Date());
			memberConsultQuestion.setIsAnswer("0");
		}else{
			memberConsultAnswer.setType("1");
			//更改问题回答状态
			memberConsultQuestion.setUpdateBy(appUser.getUsername());
			memberConsultQuestion.setUpdateDate(new Date());
			memberConsultQuestion.setIsAnswer("1");
		}
		
		memberConsultAnswer.setCreateBy(appUser.getUsername());
		memberConsultAnswer.setCreateDate(new Date());
		memberConsultAnswer.setUpdateBy(appUser.getUsername());
		memberConsultAnswer.setUpdateDate(new Date());
		
		memberConsultQuestionService.save(memberConsultQuestion);
		memberConsultAnswerService.save(memberConsultAnswer);
		return OperationResult.buildSuccessResult();
	}

	public OperationResult getDetailtAnswers(Long memberQuestionId) {
		Map<String, Object>data=new HashMap<String, Object>();
		//获取问题以及问题提问者信息
		MemberConsultQuestion mQuestions = memberConsultQuestionService.get(memberQuestionId);
		data.put("mQuestions", mQuestions);
		
		//获取问题回复列表，按照创建时间正序排列
		MemberConsultAnswer memberConsultAnswer=new MemberConsultAnswer();
		memberConsultAnswer.setMemberQuestionId(memberQuestionId);
		List<MemberConsultAnswer> answerLists = memberConsultAnswerService.findList(memberConsultAnswer);
		data.put("answerLists", answerLists);
		return OperationResult.buildSuccessResult(data);
	}

	public OperationResult getServerType() {
		return OperationResult.buildSuccessResult(serverService.findAllList());
	}

	public OperationResult applyExpert(ExpertUser expertUser,HttpServletRequest request) {
		AppUser appUser= AppUserUtils.getCurrentUser(request);
		Long userId = appUser.getId();
		if(expertUserService.hasApply(appUser.getId())){
			return OperationResult.buildFailureResult("已经提交申请，请等待审批结果！");
		}
		String serverId = expertUser.getServerId();
		List<ServerUserRel>serverUserRels=new ArrayList<ServerUserRel>();
		if(StringUtils.isBlank(serverId)){
			return OperationResult.buildFailureResult("ERP类型不能为空！");
		}else{
			String[] serverIds = serverId.split(",");
			for (String id : serverIds) {
				ServerUserRel serverUserRel=new ServerUserRel(userId, Long.parseLong(id), new Date(), new Date());
				serverUserRels.add(serverUserRel);
			}
		}
		//往专家表插入记录
		expertUser.setCreateBy(appUser.getUsername());
		expertUser.setCreateDate(new Date());
		expertUser.setUpdateBy(appUser.getUsername());
		expertUser.setUpdateDate(new Date());
		expertUser.setStatus("0");//默认待审批状态
		expertUser.setUserId(appUser.getId());
		expertUser.setCity(appUser.getCityName());
		expertUser.setProvince(appUser.getProvincialName());
		expertUser.setNickname(appUser.getNickname());
		expertUserService.save(expertUser);
		serverUserRelService.insertBatch(serverUserRels);
		//在申请记录表插入数据
		ExpertApprovalRecord expertApprovalRecord=new ExpertApprovalRecord();
		//expertApprovalRecord
		expertApprovalRecord.setUserId(appUser.getId());
		expertApprovalRecord.setServerId(expertUser.getServerId());
		expertApprovalRecord.setCreateBy(appUser.getUsername());
		expertApprovalRecord.setUpdateBy(appUser.getUsername());
		expertApprovalRecord.setCreateDate(new Date());
		expertApprovalRecord.setUpdateDate(new Date());
		expertApprovalRecord.setStatus("0");//默认待审批状态
		expertApprovalRecordService.insert(expertApprovalRecord);
		return OperationResult.buildSuccessResult("申请提交成功，请等待审批结果！");
	}

	public OperationResult getApplyStatus(Long userId) {
		ExpertApprovalRecord expertApply=expertApprovalRecordService.getApplyStatus(userId);
		return OperationResult.buildSuccessResult(expertApply);
	}

	public OperationResult editAppUser(AppUser appUser,HttpServletRequest request, MultipartFile file) {
		 String username=appUser.getUsername();
		 if(StringUtils.isBlank(username)){
			 return OperationResult.buildFailureResult("手机号不能为空！");
		 }
		 AppUser oldUser = appUserService.findAppUserByUserName(username);
		 if(oldUser==null){
			 return OperationResult.buildFailureResult("该用户不存在！");
		 }
		 if(oldUser.getId().compareTo(appUser.getId())!=0){
			 return OperationResult.buildFailureResult("手机号已经存在！");
		 }
		 if(file!=null){
			 String fileName = file.getOriginalFilename();
		     fileName = FileUtil.renameToUUID(fileName);
		     File sysFile = new File(FileType.fileType(fileName), "/files/" + fileName, new Date());
		     try {
				FileUtil.uploadFile(file, bootdoConfig.getUploadPath(), fileName);
			} catch (Exception e) {
				logger.error("上传头像失败！",e);
				return OperationResult.buildFailureResult("上传头像失败！");
			}
		    sysFileService.save(sysFile);
		    
		    appUser.setImageUrl(sysFile.getUrl()); 
		 }
		
	    appUser.setUpdateBy(appUser.getUsername());
	    appUser.setUpdateDate(new Date());
	    appUser.setMobile(username);
	    appUserService.update(appUser);
		return OperationResult.buildSuccessResult("修改成功!",appUserService.get(appUser.getId()));
	}

	public OperationResult askQuestions(MemberConsultQuestion memberConsultQuestion, HttpServletRequest request) {
		AppUser appUser=AppUserUtils.getCurrentUser(request);
		memberConsultQuestion.setIsAnswer("0");
		memberConsultQuestion.setCreateBy(appUser.getUsername());
		memberConsultQuestion.setCreateDate(new Date());
		memberConsultQuestion.setUpdateBy(appUser.getUsername());
		memberConsultQuestion.setUpdateDate(new Date());
		memberConsultQuestionService.insert(memberConsultQuestion);
		return OperationResult.buildSuccessResult();
	}
	
}
